// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

// ************************************************************************* //
//                              avtBinaryAddExpression.C                     //
// ************************************************************************* //

#include <avtBinaryAddExpression.h>

#include <vtkDataArray.h>
#include <vtkDataArray.h>

#include <ExpressionException.h>
#ifdef _OPENMP
#include <StackTimer.h>
#include <omp.h>
#endif

// ****************************************************************************
//  Method: avtBinaryAddExpression constructor
//
//  Purpose:
//      Defines the constructor.  Note: this should not be inlined in the
//      header because it causes problems for certain compilers.
//
//  Programmer: Hank Childs
//  Creation:   February 5, 2004
//
// ****************************************************************************

avtBinaryAddExpression::avtBinaryAddExpression()
{
    ;
}


// ****************************************************************************
//  Method: avtBinaryAddExpression destructor
//
//  Purpose:
//      Defines the destructor.  Note: this should not be inlined in the header
//      because it causes problems for certain compilers.
//
//  Programmer: Hank Childs
//  Creation:   February 5, 2004
//
// ****************************************************************************

avtBinaryAddExpression::~avtBinaryAddExpression()
{
    ;
}


// ****************************************************************************
//  Method: avtBinaryAddExpression::DoOperation
//
//  Purpose:
//      Sums two arrays into a third array.
//
//  Arguments:
//      in1           The first input data array.
//      in2           The second input data array.
//      out           The output data array.
//      ncomponents   The number of components ('1' for scalar, '2' or '3' for
//                    vectors, etc.)
//      ntuples       The number of tuples (ie 'npoints' or 'ncells')
//
//  Programmer: Sean Ahern          <Header added by Hank Childs>
//  Creation:   November 18, 2002   <Header creation date>
//
//  Modifications:
//
//    Hank Childs, Mon Nov 18 07:35:07 PST 2002
//    Added support for vectors and arbitrary data types.
//
//    Hank Childs, Thu Aug 14 11:40:23 PDT 2003
//    Added support for mixing scalars and vectors.
//
//    Hank Childs, Sun Jan 13 20:11:35 PST 2008
//    Add support for singleton constants.
//
//    Brad Whitlock, Fri Jan 12 14:19:53 PST 2018
//    Special case for same #comps. OpenMP support.
//
// ****************************************************************************

void
avtBinaryAddExpression::DoOperation(vtkDataArray *in1, vtkDataArray *in2,
                                vtkDataArray *out, int ncomponents,int ntuples)
{
    bool var1IsSingleton = (in1->GetNumberOfTuples() == 1);
    bool var2IsSingleton = (in2->GetNumberOfTuples() == 1);
    int in1ncomps = in1->GetNumberOfComponents();
    int in2ncomps = in2->GetNumberOfComponents();
    if (in1ncomps == in2ncomps)
    {
        bool handled = false;

        if(in1->HasStandardMemoryLayout() &&
           in2->HasStandardMemoryLayout() &&
           in1->GetDataType() == in2->GetDataType() &&
           // We don't want to add in these precisions because we'd probably
           // overflow when adding. These types will be handled the SetComponent
           // way.
           in1->GetDataType() != VTK_BIT &&
           in1->GetDataType() != VTK_CHAR &&
           in1->GetDataType() != VTK_SIGNED_CHAR &&
           in1->GetDataType() != VTK_UNSIGNED_CHAR &&
           in1->GetDataType() != VTK_SHORT &&
           in1->GetDataType() != VTK_UNSIGNED_SHORT)
        {

#define COMPUTE_ADD1(VARTYPE, LOW, HIGH) \
{ \
    VARTYPE *v1 = (VARTYPE *)in1->GetVoidPointer(0); \
    VARTYPE *v2 = (VARTYPE *)in2->GetVoidPointer(0); \
    VARTYPE *vout = (VARTYPE *)out->GetVoidPointer(0); \
    if(!var1IsSingleton && !var2IsSingleton) \
    { \
        for (int j = LOW ; j < HIGH ; j++) \
            vout[j] = v1[j] + v2[j]; \
    } \
    else if(!var1IsSingleton && var2IsSingleton) \
    { \
        for (int j = LOW ; j < HIGH ; j++) \
            vout[j] = v1[j] + v2[0]; \
    } \
    else if(var1IsSingleton && !var2IsSingleton) \
    { \
        for (int j = LOW ; j < HIGH ; j++) \
            vout[j] = v1[0] + v2[j]; \
    } \
    else/*if(var1IsSingleton && var2IsSingleton)*/ \
    { \
        for (int j = LOW ; j < HIGH ; j++) \
            vout[j] = v1[0] + v2[0]; \
    } \
}

#define COMPUTE_ADD(VARTYPE, LOW, HIGH) \
{ \
    VARTYPE *v1 = (VARTYPE *)in1->GetVoidPointer(0); \
    VARTYPE *v2 = (VARTYPE *)in2->GetVoidPointer(0); \
    VARTYPE *vout = (VARTYPE *)out->GetVoidPointer(0); \
    int cLow = LOW * in1ncomps; \
    int cHigh = HIGH * in1ncomps; \
    if(!var1IsSingleton && !var2IsSingleton) \
    { \
        for (int j = cLow ; j < cHigh ; j++) \
            vout[j] = v1[j] + v2[j]; \
    } \
    else if(!var1IsSingleton && var2IsSingleton) \
    { \
        for (int j = cLow ; j < cHigh ; j++) \
            vout[j] = v1[j] + v2[j % in1ncomps]; \
    } \
    else if(var1IsSingleton && !var2IsSingleton) \
    { \
        for (int j = cLow ; j < cHigh ; j++) \
            vout[j] = v1[j % in1ncomps] + v2[j]; \
    } \
    else/*if(var1IsSingleton && var2IsSingleton)*/ \
    { \
        for (int j = cLow ; j < cHigh ; j++) \
            vout[j] = v1[j % in1ncomps] + v2[j % in1ncomps]; \
    } \
}

#ifdef _OPENMP
            StackTimer t0("avtBinaryAddExpression OpenMP");
            #pragma message("Compiling for OpenMP.")
            #pragma omp parallel
            {
                int threadnum = omp_get_thread_num();
                int numthreads = omp_get_num_threads();
                int low = ntuples*threadnum/numthreads;
                int high = ntuples*(threadnum+1)/numthreads;
#else
                int low = 0, high = ntuples;
#endif
                if(in1ncomps == 1)
                {
                    switch(in1->GetDataType())
                    {
                        vtkTemplateMacro(COMPUTE_ADD1(VTK_TT, low, high));
                    }
                    handled = true;
                }
                else
                {
                    switch(in1->GetDataType())
                    {
                        vtkTemplateMacro(COMPUTE_ADD(VTK_TT, low, high));
                    }
                    handled = true;
                }
#ifdef _OPENMP
            }
#endif
        }

        if(!handled)
        {
            for (int i = 0 ; i < ntuples ; i++)
            {
                vtkIdType tup1 = (var1IsSingleton ? 0 : i);
                vtkIdType tup2 = (var2IsSingleton ? 0 : i);
                for (int j = 0 ; j < in1ncomps ; j++)
                {
                    double val1 = in1->GetComponent(tup1, j);
                    double val2 = in2->GetComponent(tup2, j);
                    out->SetComponent(i, j, val1 + val2);
                }
            }
        }
    }
    else if (in1ncomps > 1 && in2ncomps == 1)
    {
        for (int i = 0 ; i < ntuples ; i++)
        {
            vtkIdType tup1 = (var1IsSingleton ? 0 : i);
            vtkIdType tup2 = (var2IsSingleton ? 0 : i);
            double val2 = in2->GetTuple1(tup2);
            for (int j = 0 ; j < in1ncomps ; j++)
            {
                double val1 = in1->GetComponent(tup1, j);
                out->SetComponent(i, j, val1 + val2);
            }
        }
    }
    else if (in1ncomps == 1 && in2ncomps > 1)
    {
        for (int i = 0 ; i < ntuples ; i++)
        {
            vtkIdType tup1 = (var1IsSingleton ? 0 : i);
            vtkIdType tup2 = (var2IsSingleton ? 0 : i);
            double val1 = in1->GetTuple1(tup1);
            for (int j = 0 ; j < in2ncomps ; j++)
            {
                double val2 = in2->GetComponent(tup2, j);
                out->SetComponent(i, j, val1 + val2);
            }
        }
    }
    else
    {
        EXCEPTION2(ExpressionException, outputVariableName,
                   "Don't know how to add vectors of differing dimensions.");
    }
}


// ****************************************************************************
//  Method:  avtBinaryAddExpression::GetVariableType
//
//  Purpose:
//    Better support for array variables.  We actually return the output
//    type to be the same as the input type (assuming they are the same,
//    or if one has 1 compoent).
//
//  Note:
//    This can't yet be pulled up into avtBinaryMathExpression because
//    mult and div do non-elementwise operations.  If that changes,
//    we should pull this up.
//
//  Arguments:
//    none
//
//  Programmer:  Jeremy Meredith
//  Creation:    March 18, 2009
//
// ****************************************************************************

avtVarType
avtBinaryAddExpression::GetVariableType()
{
    avtDataAttributes &atts = GetInput()->GetInfo().GetAttributes();
    if (varnames.size() != 2)
        return AVT_UNKNOWN_TYPE;

    if (!atts.ValidVariable(varnames[0]) ||
        !atts.ValidVariable(varnames[1]))
        return AVT_UNKNOWN_TYPE;

    int ncomp1 = atts.GetVariableDimension(varnames[0]);
    int ncomp2 = atts.GetVariableDimension(varnames[1]);
    avtVarType type1 = atts.GetVariableType(varnames[0]);
    avtVarType type2 = atts.GetVariableType(varnames[1]);

    if (type1 == type2)
    {
        return type1;
    }
    else if (ncomp1 == 1)
    {
        return type2;
    }
    else if (ncomp2 == 1)
    {
        return type1;
    }
    else
    {
        return AVT_UNKNOWN_TYPE;
    }
}
